<?php
namespace App\Http\Controllers;

use App\Http\Model\AdminEquipSysConfig;
use App\Http\Model\FinanceRechargeOrder;
use App\Http\Model\FinanceUserWallet;
use Illuminate\Http\Request;
use App\Lib\Response;
use App\Http\Model\Hint;
use App\Http\Model\UnionUser;
use App\Http\Services\SystemServices;
use App\Http\Services\UserServices;
use App\Http\Services\GameServices;
use Carbon\Carbon;
use App\Http\Services\ThinkingdataServices;
use App\Model\FinanceWallet;
use Illuminate\Support\Facades\Redis;

class ApiSystemController  extends BaseController
{
    protected $services_system;
    protected $services_user;
    protected $deviceServices;
    protected $helpServices;
    protected $gameService;
    protected $AdminEquipSysConfig;
    protected $model_union_user;
    protected $financeRechargeModel;
    protected $tdService;
    protected $financeWaletModel;

    protected $anchorLiveTime = 'MICLIVETIME:USER:';//主播总开播时长 string
    protected $crossRoomPkOpen = 'CROSS:ROOM:PK:OPEN';//开关跨房 string CROSS:ROOM:PK:OPEN=>1或0

    public function __construct(){
        $this->services_system = new SystemServices();
        $this->services_user = new UserServices();
        $this->gameService = new GameServices();
        $this->AdminEquipSysConfig = new AdminEquipSysConfig();
        $this->model_union_user = new UnionUser();
        $this->financeRechargeModel = new FinanceRechargeOrder();
        $this->financeWaletModel = new FinanceUserWallet();
        $this->tdService = new ThinkingdataServices();
    }

    public function get_init(Request $request){

        $platform_id = (int) $request->get("platform_id");
        $channel_id = (int) $request->get("channel_id");
        $version_id = (string) $request->get("version_id");
        $version_code = (string) $request->get("version_code");

        if(!$platform_id || !$channel_id || !$version_id){

            Response::returnResult(Hint::PARAM_ERROR);
        }
        $app_ua = $this->services_system->parse_app_UA();

        $userInfo = $this->services_user->get_current_user();

        $userId = $userInfo['user_id'] ?? 0;
        if($userId) {
            $this->services_user->setOsVersion($userId, $app_ua['version_no']);
        }

        $configMap = [];
        $config = $this->services_system->get_config();
        foreach ($config as $k => $v){
            $value = $v['value'];
            if ($v['type'] == 1){
                $value = intval($v['value']);
            }
            $configMap[$k] = $value;
        }

        //更新用户渠道
        // $this->services_user->update_channel_guid();
        $data = [];
        $data['time'] = time();
        //全局飘屏限制
        $data['show_screen_premission'] = [
            "show_full_screen" => 0,//全局显示飘屏限制0不展示 1=展示
            "special_wish_wheel_screen" => 0,//许愿转盘飘屏/公屏权限 1=可以看到 0=不可以看到
            "special_wish_pool_screen" => 0,//许愿池飘屏/公屏权限 1=可以看到 0=不可以看到
        ];
        //获取拍卖公共聊天权限
        $isOpen = $this->getUserOpenPermisson($userId,$userInfo);
        //版本更新
        $data['version'] = $this->services_system->get_last_version($platform_id, $channel_id);
        if(!empty($data['version']['version_id']) && !empty($version_id)){
            if (version_compare($data['version']['version_id'], $version_id) <= 0){
                $data['version']['upgrade_type'] = 0;
            }
        }
        //青少年
        $data['teenager'] = isset($configMap['teenager']) ? $configMap['teenager'] : 0;
        $data['teenager_policy'] = isset($configMap['teenager_policy']) ? $configMap['teenager_policy'] : '';
        //用户注册协议
        $data['user_protocol_url'] = isset($configMap['user_protocol_url']) ? $configMap['user_protocol_url'] : '';
        //隐私协议
        $data['policy_url'] = isset($configMap['policy_url']) ? $configMap['policy_url'] : '';
        //房间提醒内容
        $data['room_remind'] = isset($configMap['room_remind']) ? $configMap['room_remind'] : '';
        //全服信息
        $data['chat_room_id'] = config('rong_cloud.chat_room_id');
        //拍卖公聊权限
        $data['auction'] = [
            'is_open' => $isOpen,//用户是否有权限
            'auction_room_id' => 99,//公聊厅id
        ];
        //客服url
        $data['kefu_url'] = isset($configMap['kefu_url']) ? $configMap['kefu_url'] : '';
        //充值协议
        $data['recharge_protocol'] = isset($configMap['recharge_protocol']) ? $configMap['recharge_protocol'] : '';
        //注销规则
        $data['account_cancel_url'] = isset($configMap['account_cancel_url']) ? $configMap['account_cancel_url'] : '';
        //h5充值url
        $data['h5_recharge_url'] = isset($configMap['h5_recharge_url']) ? $configMap['h5_recharge_url'] : '';
        //h5提现url
        $data['h5_withdraw_url'] = isset($configMap['h5_withdraw_url']) ? $configMap['h5_withdraw_url'] : '';
        //公会细则
        $data['union_help_url'] = isset($configMap['union_help_url']) ? $configMap['union_help_url'] : '';
        //分享h5链接
        $data['share_h5_url'] = isset($configMap['share_h5_url']) ? $configMap['share_h5_url'] : '';

        //金币兑换钻石比例
//        $config = config('pay');
//        $kk_to_diamond = $config['wallet_change_ratio']['kk_to_diamond'];
        $data['kk_to_withdraw'] = isset($configMap['kk_to_withdraw']) ? $configMap['kk_to_withdraw'] : '';
        $data['kk_to_diamond'] = isset($configMap['kk_to_diamond']) ? $configMap['kk_to_diamond'] : '';

        //邀请相关
        $data['share_invite_url'] = isset($configMap['share_invite_url']) ? $configMap['share_invite_url'] : '';
        $data['open_code_url'] = "";
        $queryStr = '?';
        if (!empty($data['share_invite_url'])){
            $queryStr = parse_url($data['share_invite_url'], PHP_URL_QUERY) ? '&' : '?';
        }
        if ($userInfo && $userInfo['is_open_code'] == 1) {
            $data['open_code_url'] = $data['share_invite_url'] . $queryStr .'user_id='.$userId;
        }
        $data['open_code']['is_open_code'] = $userInfo['is_open_code'] == 1 ? 1 : 0;
        $data['open_code']['share']['title'] = isset($configMap['share_invite_title']) ? $configMap['share_invite_title'] : '';
        $data['open_code']['share']['msg'] = isset($configMap['share_invite_msg']) ? $configMap['share_invite_msg'] : '';
        $data['open_code']['share']['image'] = isset($configMap['share_invite_image']) ? build_image($configMap['share_invite_image']) : '';
        $data['open_code']['share']['url'] = $data['share_invite_url'] . $queryStr .'user_id='.$userId;

        //分享活动链接
        $data['share_activity_url'] = isset($configMap['share_activity_url']) ? $configMap['share_activity_url'] : '';

        //财富等级地址
        $data['finance_rank_url'] = isset($configMap['finance_rank_url']) ? $configMap['finance_rank_url'] : '';
        //官方运营微信
        $data['operate_wechat'] = isset($configMap['operate_wechat']) ? $configMap['operate_wechat'] : '';
        //提现须知
        $feilv=(1-$data['kk_to_withdraw'])*100;
        $data['withdraw_notice'] = isset($configMap['withdraw_notice']) ? $configMap['withdraw_notice'].$feilv.'%': '';
        //提现协议h5
        $data['extract_protocol'] = isset($configMap['extract_protocol']) ? $configMap['extract_protocol'] : '';
        //提现规则h5
        $data['extract_rule'] = isset($configMap['extract_rule']) ? $configMap['extract_rule'] : '';
        //每局机器人花费钻石
        $data['game_ai_diamond'] = $this->gameService->gameAiDiamond;
        //ios审核开关
        $data['iOS_appstore'] = isset($configMap['iOS_appstore']) ? json_decode($configMap['iOS_appstore'], true) : null;
        //ios审核是否展示房间开关 0=展示 1=不展示
        $data['apply_open_room'] = isset($configMap['apply_open_room']) ? $configMap['apply_open_room'] : 0;
        //ios审核用户userId列表
        $data['apply_user_id_list'] = isset($configMap['apply_user_id_list']) ? json_decode($configMap['apply_user_id_list'], true) : null;
        //我的页面点击娱乐等级图标跳转到H5余娱乐等级中心页面
        $data['user_click_game_jump'] = isset($configMap['user_click_game_jump']) ? $configMap['user_click_game_jump'] : '';
        //安卓版本功能限制 0=不限制 1限制
        $data['android_version_intercept'] = isset($configMap['android_version_intercept']) ? json_decode($configMap['android_version_intercept'], true) : null;
        //iOS版本功能限制 0=不限制 1限制
        $data['ios_version_intercept'] = isset($configMap['ios_version_intercept']) ? json_decode($configMap['ios_version_intercept'], true) : null;
        //阿里云验证码
        $data['aliVerify'] = $this->services_system->getAliVerify();
        //跨房PK开关1=开启 0=关闭
        $data['cross_pk_open'] = isset($configMap['cross_pk_open']) ? $configMap['cross_pk_open'] : 0;
        //送礼公屏信息钻石限制
        $data['take_msg_gift'] = isset($configMap['take_msg_gift']) ? $configMap['take_msg_gift'] : 0;
        //系统配置飘屏权限限制
        $sys_show_full_screen =  isset($configMap['full_screen_cofing']) ? $configMap['full_screen_cofing'] : [];
        $sys_show_full_screen = json_decode($sys_show_full_screen,true);
        
        if(!empty($userId) && !empty($sys_show_full_screen)){
            //查看用户财富值是否大与系统配置飘屏财富值
            $userRechargeDiamond = $this->financeWaletModel->get_wallet($userId);
            foreach($sys_show_full_screen as $k=>$val){
                if($userRechargeDiamond['wealth_balance'] >= $val){
                    $data['show_screen_premission'][$k] = 1;
                }
            }
        }
        //自定义充值1=开启 0=关闭
        $data['custom_recharge'] = isset($configMap['custom_recharge']) ? $configMap['custom_recharge'] : 0;
        //关于我们配置
        $aboutUs = isset($configMap['about_us']) ? $configMap['about_us'] : [];
        $aboutUs = json_decode($configMap['about_us'],true);
        $data['about_us'] = $aboutUs;
        //官方客服
        $data['official_service'] = 18;//密码 1234qwert
        //客服是否显示
        $data['official_show'] = isset($configMap['official_show']) ? $configMap['official_show'] : 0;

        Response::returnResult(Hint::SUCCESS, $data);
    }

    //获取公聊拍卖权限
    public function getUserOpenPermisson($userId, $userInfo){
        if(empty($userId)){
            return 0;
        }
        do{
            $isOpen = 1;
            //查看用户是否满足公聊厅条件
            $chatConfig = $this->AdminEquipSysConfig->getConfig();
            if(empty($chatConfig)){
                $isOpen = 0;
                break;
            }
            //判断用户是否是主播身份
            $userType = $this->model_union_user->getUnionByUser([$userId]);
            //获取主播钱包信息
            $userWalet = $this->services_user->getResponseData($userId);
            if(!empty($userType)){
                //主播财富值小于设置值
               if($userWalet['wealth_balance'] < $chatConfig['min_rich_value']){
                    $isOpen = 0;
                    break;
               }
               //主播财富值大于设置值
               if($userWalet['wealth_balance'] > $chatConfig['max_rich_value']){
                    $isOpen = 0;
                    break;
               }
               //主播魅力值小于设置值
               if($userWalet['charm_balance'] < $chatConfig['min_charm_value']){
                    $isOpen = 0;
                    break;
               }
               //主播魅力值大于设置值
               if($userWalet['charm_balance'] > $chatConfig['max_charm_value']){
                    $isOpen = 0;
                    break;
               }
               //主播开播时长小于设置时长
               $liveTime = empty(Redis::get($this->anchorLiveTime.$userId)) ? 0 : Redis::get($this->anchorLiveTime.$userId);
                $liveMinutes = $liveTime/60;
               if($liveMinutes < $chatConfig['mic_all_time']){
                    $isOpen = 0;
                    break;
               }
            }else{
                //判断用户最小财富值小于设置值
                if($userWalet['wealth_balance'] < $chatConfig['min_user_rich_value']){
                    $isOpen = 0;
                    break;
                }
                //判断用户最大财富值大于设置值
                if($userWalet['wealth_balance'] > $chatConfig['max_user_rich_value']){
                    $isOpen = 0;
                    break;
                }
                //判断用户最小充值金额小于设置值
                $userRecharge = $this->financeRechargeModel->getRechargeTotal($userId);
                if($userRecharge/100 < $chatConfig['min_user_recharge_value']){
                    $isOpen = 0;
                    break;
                }
                if($userRecharge/100 > $chatConfig['max_user_recharge_value']){
                    $isOpen = 0;
                    break;
                }
                //判断用户注册天数差是否小于配置天数
                $now = Carbon::now()->toDateTimeString();
                $registeDay = Carbon::parse($now)->diffInDays(date('Y-m-d H:i:s',$userInfo['create_timestamp']));
                if($registeDay < $chatConfig['after_day']){
                    $isOpen = 0;
                    break;
                }
            }
        }while(false);
        return $isOpen;
    }

    public function get_version(Request $request){
        if(!$request->get('platform_id')){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if(!$request->get('channel_id')){
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $platform_id = $request->get("platform_id");
        $channel_id = $request->get("channel_id");
        $version_id = (string) $request->get("version_id");
        $version_code = (string) $request->get("version_code");

        $version_item = $this->services_system->get_last_version($platform_id, $channel_id);

        if (empty($version_item)){
            Response::returnResult(Hint::SYSTEM_NOVER, [], '当前已是最新版本');
        }
        if (version_compare($version_item['version_id'] , $version_id) <= 0){
            Response::returnResult(Hint::SYSTEM_NOVER, [], '当前已是最新版本12');
        }

        //判断当前是否是最新版本
        $version_item['is_new'] = $version_id == $version_item['version_id'];
        Response::returnResult(Hint::SUCCESS, $version_item);
    }

    /**
     * 文件上传获取路径
     */
    public function get_put_file_url(Request $request){
        if(!$request->get("type")){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if(!$request->get("exts")){
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $type = $request->get("type");
        $exts = $request->get("exts");

        $data = $this->services_system->get_put_file_url($type, $exts);
        if($data == null){
            Response::returnResult(Hint::LOGIN_OUT);
        }
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 根据获取版本数据
     * */
    public function getSystemVersion()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'getSystemVersion', $this->requestData,false);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 获取系统说明信息
     */
    public function getExplain(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'getExplain', $this->requestData);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    ################# 统一验证码模块 ##########################################

    /**
     * 获取图形验证码
     * */
    public function captchaCode()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'captchaCode', $this->requestData, false);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 校验图形验证码
     * */
    public function checkCaptchaCode()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'checkCaptchaCode', $this->requestData, false);

            // TODO 校验成功
            if ($this->responseData['code'] == Hint::SUCCESS) {
                // TODO 记录操作手机号时间
                $this->services_system->requestData['phone'] = $this->responseData['data']['phone'];
                $this->services_system->recordPhoneOpTime();
            }

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 获取表情最后版本
     * */
    public function get_expression_new_version(Request $request){
        $version_item = $this->services_system->get_expression_new_last_version();
        if (empty($version_item)){
            Response::returnResult(Hint::SYSTEM_NOVER);
        }
        Response::returnResult(Hint::SUCCESS, $version_item);
    }

    /**
     * 阿里云验证码校验
     * */
    public function aliVerify(Request $request)
    {
        $captchaVerifyParam = $request->input('captchaVerifyParam');
        $phone = $request->input('phone');
        if (empty($captchaVerifyParam)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $result = $this->services_system->aliVerify($captchaVerifyParam,$phone);

        Response::returnResult($result['code'],$result['data'],$result['msg']);
    }

    /**
     * 埋点上报
     * */
    public function buryPoint(Request $request){
        $userId = $this->getLoginUserId();
        $data['type'] = $request->input('type');
        $data['room_id'] = $request->input('room_id');
        $data['thoroughfare'] = $request->input('thoroughfare');
        $data['click_type'] = $request->input('click_type');
        $data['action_type'] = $request->input('action_type');

        //埋点
        $this->tdService->buryPoint($userId, $data);

        Response::returnResult(Hint::SUCCESS);
    }
    public function musicSearchList(Request $request)
    {

        $word=$request->input('searchname');
        $word=urlencode($word);
        $type=$request->input('type');

        if (empty($word)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (empty($type)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $limit=empty($request->input('limit'))?20:$request->input('limit');
        $offset=empty($request->input('offset'))?0:$request->input('offset');
        $url ="https://music.163.com/api/cloudsearch/pc?s=$word&offset=$offset&limit=$limit&type=$type";
        $result=file_get_contents($url);
//        $data=json_decode($result,true);
       if($type==1){
           $data = [];
           $res=json_decode($result,true);

           foreach ($res['result']['songs'] as $k=>$v){
               $data[$k]['name']=$v['name'];
               $data[$k]['id']=$v['id'];
               foreach ($v['ar'] as $kk=>$vv){
               }
               $data[$k]['author']=$vv['name'];

               $data[$k]['br']=$v['h']['br'];
           }
//           $data['code']=$res['code'];

       }else{
           $data=json_decode($result,true);
       }

        if($res['code'] == 200){
            $ress['code'] = 0;
            $ress['msg'] = "成功";
            $ress['data'] = $data;
            $jsonStr = json_encode($ress,JSON_UNESCAPED_UNICODE);
            return $jsonStr;

//            Response::returnResult(Hint::SUCCESS, array_values($data));
        }else{
            Response::returnResult(Hint::PARAM_ERROR, '网易云连接失败');
            write_log('music', 'musicSearchDetail', $result);
        }


    }
    public function musicSearchDetail(Request $request)
    {
        $ids=$request->input('ids');
        if (empty($ids)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $url = "https://music.163.com/api/song/detail?ids=$ids";
        $result=file_get_contents($url);
        $res=json_decode($result,true);

        foreach ($res['songs'] as $k => $v){
            $data['id']=$v['id'];
            $data['name']=$v['name'];
            $data['artists']=$v['artists'];
            $data['album']=$v['album'];
        }
        $data['code']=$res['code'];

        if($data['code'] == 200){

            Response::returnResult(Hint::SUCCESS, $data);
        }else{

            Response::returnResult(Hint::PARAM_ERROR, '网易云连接失败');
            write_log('music', 'musicSearchDetail', $result);
        }


    }
    public function musicSearchAddress(Request $request)
    {
        $ids=$request->input('ids');
        $br=$request->input('br');
        if (empty($ids)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (empty($br)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $url = "https://music.163.com/api/song/enhance/player/url?ids=$ids&br=$br";

        $result=file_get_contents($url);
        $res=json_decode($result,true);
        foreach ($res['data'] as $k => $v){
            $data['id']=$v['id'];
            $data['url']=$v['url'];
            $data['br']=$v['br'];
            $data['type']=$v['type'];
            $data['time']=$v['time'];
        }
        $data['code']=$res['code'];

        if($data['code'] == 200){
            Response::returnResult(Hint::SUCCESS, $data);
        }else{
            Response::returnResult(Hint::PARAM_ERROR, '网易云连接失败');
            write_log('music', 'musicSearchDetail', $result);
        }


    }

    public function musicSearchList2(Request $request)
    {

        $word=$request->input('searchname');
        $word=urlencode($word);
        $type=$request->input('type');

        if (empty($word)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (empty($type)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $limit=empty($request->input('limit'))?20:$request->input('limit');
        $offset=empty($request->input('offset'))?0:$request->input('offset');
        $url ="https://music.163.com/api/cloudsearch/pc?s=$word&offset=$offset&limit=$limit&type=$type";
        $result=file_get_contents($url);
//        $data=json_decode($result,true);
        if($type==1){
            $data = [];
            $res=json_decode($result,true);

            foreach ($res['result']['songs'] as $k=>$v){
                $data[$k]['name']=$v['name'];
                $data[$k]['id']=$v['id'];
                foreach ($v['ar'] as $kk=>$vv){
                }
                $data[$k]['author']=$vv['name'];

                $data[$k]['br']=$v['h']['br'];
            }
//            $data['code']=$res['code'];

        }


        if($res['code'] == 200){

            $ress['code'] = 0;
            $ress['msg'] = "成功";
            $ress['data'] = $data;
            $jsonStr = json_encode($ress,JSON_UNESCAPED_UNICODE);
            return $jsonStr;
//            Response::returnResult(Hint::SUCCESS, array_values($data));
        }else{
            Response::returnResult(Hint::PARAM_ERROR, '网易云连接失败');
            write_log('music', 'musicSearchDetail', $result);
        }


    }
}
